package org.bright.util;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;

public class OrderIdGenerator {
    /*
     * 前8位：日期（YYYYMMDD）
     * 中间4位：当天的序列号（从0001开始）
     * 后4位：随机数（用于增加安全性）
     *
     */
    private static final AtomicInteger sequence = new AtomicInteger(0);
    private static final Random random = new Random();
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");

    public synchronized static String generateOrderId() {
        // 获取当前日期
        String datePart = dateFormat.format(new Date());

        // 生成当天的序列号
        int seq = sequence.incrementAndGet();
        if (seq > 9999) {
            throw new IllegalStateException("Too many orders in one day");
        }
        String seqStr = String.format("%04d", seq);

        // 生成随机数
        String randomPart = String.format("%04d", random.nextInt(10000));

        // 拼接成完整的订单ID
        return datePart + seqStr + randomPart;
    }

    public static void main(String[] args) {
        OrderIdGenerator generator = new OrderIdGenerator();
        for (int i = 0; i < 5; i++) {
            System.out.println(generator.generateOrderId());
        }
    }

}
